#include "myrpcapplication.h"
#include <iostream>
#include <unistd.h>

// 类外初始化静态变量
MyRPCConfig MyRPCApplication::m_config; 
// 懒汉式
MyRPCApplication* MyRPCApplication::m_application = nullptr; 
std::mutex MyRPCApplication::m_mutex;

void MyRPCApplication::init(int argc, char** argv) {
    if (argc < 2) {
        // 参数个数少于2
        std::cout << "format:command -i <configfile> \n";
        exit(EXIT_FAILURE);
    }
    int o;
    std::string config_file;
    // getopt函数来解析命令行选项后面的参数
    while(-1 != (o = getopt(argc,argv,"i:"))) { 
        switch(o) {
            case 'i':
                // -i 参数后面跟着的是配置文件的路径
                config_file = optarg;
                break;
            case '?':
                // 遇到了未指定选项的参数
                std::cout << "format:command -i <configfile> \n";
                exit(EXIT_FAILURE);
                break;
            case ':':
                // 指定了选项但是没有参数值
                std::cout << "format:command -i <configfile> \n";
                exit(EXIT_FAILURE);
                break;
            default:
                break;
        }
    }
    // 加载配置文件
    m_config.loadConfigFile(config_file.c_str());
}

MyRPCApplication& MyRPCApplication::getInstance() {
    // 加锁
    std::lock_guard<std::mutex> lock(m_mutex);
    if (m_application == nullptr) {
        m_application = new MyRPCApplication();
        atexit(deleteInstance);
    }
    // 返回引用
    return *m_application;
}

void MyRPCApplication::deleteInstance() {
    if (m_application) {
        delete m_application;
    }
}

MyRPCConfig& MyRPCApplication::getConfig() {
    return m_config;
}